<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>canvas</title>
  <style>
    html,
    body {
      margin: 0;
    }

    canvas {
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <canvas id="canvas" width="500" height="320">
    你的浏览器太low了~
  </canvas>
  <script>
    window.onload = function () {
      var canvas = document.getElementById('canvas')
      if (canvas.getContext) {
        var ctx = canvas.getContext('2d')

        function Ball(x, y, r, speedx, speedy, color) {
          // 设置属性
          this.x = x;
          this.y = y;
          this.r = r;
          this.speedx = speedx;
          this.speedy = speedy;
          this.color = color;

          // 设置方法
          // 画圆
          this.draw = function () {
            ctx.beginPath();
            ctx.fillStyle = this.color;
            ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2)
            ctx.fill()
          }

          // 运动
          this.move = function () {
            this.x += this.speedx;
            this.y += this.speedy;

            if (this.x > canvas.width - this.r || this.x < this.r) {// 边界判断
              this.speedx *= -1;
            }
            if (this.y > canvas.height - this.r || this.y < this.r) {// 边界判断
              this.speedy *= -1;
            }
          }
        }



        var ball = new Ball(50, 50, 30, 2, 3, 'pink')
        ball.draw()

        function animate() {
          ctx.clearRect(0, 0, canvas.width, canvas.height)
          ball.move()
          ball.draw()
          window.requestAnimationFrame(animate)
        }
        animate()

      } else {
        alert('你的浏览器太low了~')
      }
    }
  </script>

</body>

</html>